package com.five.matebook.activity.matebook;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.five.matebook.activity.db.DbHelper;
import com.five.matebook.utils.DeviceUtils;

import java.io.File;
import java.util.Objects;

public class Matebook {
    private static final String TAG = "Matebook";
    private static final String SUFFIX = ".db";
    private String alias;
    private String id;

    private int updateCount = 0;

    public static Matebook getMatebook(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        if (!fileName.endsWith(SUFFIX)) {
            Log.e(TAG, String.format("getMatebook() not a db file: %s", fileName));
            return null;
        }
        String[] arr = fileName.replace(SUFFIX, "").split("_");
        if (arr.length != 2) {
            Log.e(TAG, String.format("getMatebook() file name not invalid: %s", fileName));
            return null;
        }
        return new Matebook(arr[0], arr[1]);
    }

    Matebook(String id, String alias) {
        this.id = id;
        this.alias = alias;
    }

    public String getFileName() {
        return String.format("%s_%s%s", id, alias, SUFFIX);
    }

    public boolean isMine() {
        return DeviceUtils.getDeviceUuid().equals(id);
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getAlias() {
        return alias;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    private boolean isDefault() {
        return DeviceUtils.getDeviceUuid().equals(id);
    }

    public int getUpdateCount() {
        return updateCount;
    }

    public void setUpdateCount(int updateCount) {
        this.updateCount = updateCount;
    }

    public void setHasUpdate(boolean hasUpdate) {
        if (hasUpdate) {
            this.updateCount++;
        } else {
            this.updateCount = 0;
        }
    }

    public File getDbFile(Context context) {
        return DbHelper.getDbFile(context, getFileName());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Matebook matebook = (Matebook) o;
        return Objects.equals(alias, matebook.alias) && Objects.equals(id, matebook.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(alias, id);
    }
}
